﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;
using System.Windows.Forms;
using System.IO;

namespace PCDoctor.Utils
{
    /// <summary>
    /// Класс для работы с настройками приложения, Singleton
    /// </summary>
    class Config
    {
        /// <summary>
        /// URL файла (XML) с параметрами новой версии
        /// </summary>
        public const string UPDATE_XML_PATH = "http://creminds.ru/update.xml";

        /// <summary>
        /// URL для проверки валидности ключа регистрации
        /// </summary>
        public const string LICENSE_CHECK_URL = "http://creminds.ru/license.php";

        /// <summary>
        /// URL активации ПО
        /// </summary>
        public const string ACTIVATION_URL = "http://creminds.ru/activate.php";

        public const string RegistryPath = "Software\\Hauberk Software\\PCDoctor";
        public const string BackupRegistryPath = "Software\\Hauberk Software\\PCDoctorBackup";

        public const string CURRENT_VERSION = "0.8";

        public const string APP_AUTOSTART = "Autostart";
        public const string APP_AUTOSCAN = "Autoscan";
        public const string APP_AUTOFIX = "Autofix";
        public const string BUTTONS_CLOSE = "Btn_Close";
        public const string BUTTONS_MINIMIZE = "Btn_Minimize";
        public const string GAMING_PRINTERS = "Game_Printers";
        public const string GAMING_SCANERS = "Game_Scaners";
        public const string GAMING_TABLET = "Game_Tablet";
        public const string GAMING_THEMES = "Game_Themes";
        public const string GAMING_AERO = "Game_Aero";
        public const string GAMING_REMOTEFILES = "Game_RemoteFiles";
        public const string GAMING_SEARCH = "Game_Search";
        public const string GAMING_MCENTER = "Game_MCenter";
        public const string GAMING_UPDATE = "Game_Update";
        public const string GAMING_DEFRAG = "Game_Defrag";
        public const string GAMING_ERRORS = "Game_Errors";
        public const string GAMING_OTHER = "Game_Other";
        public const string UPDATE_SKIP_VERSION = "Update_skip_ver";
        public const string REGISTRATION_CODE = "License_code";
        public const string REGISTRATION_STATUS = "reg";

        public const string DEMO_REG_CODE = "DEMO-DEMO-DEMO-DEMO";

        protected static Config instance = null;

        public static Config getInstance()
        {
            if (instance == null)
            {
                instance = new Config();
                instance.Load();
            }
            return instance;
        }

        public void debug()
        {
            foreach (KeyValuePair<string, string> kv in settings)
            {
                Console.WriteLine(kv.Key + " = " + kv.Value);
            }
        }

        protected IDictionary<string, string> settings = new Dictionary<string, string>();

        public string getValue(string valueName)
        {
            if (!settings.ContainsKey(valueName)) return "";
            return settings[valueName];
        }

        public void setValue(string valueName, string value)
        {
            if (!settings.ContainsKey(valueName))
            {
                settings.Add(valueName, value);
            }
            else
            {
                settings[valueName] = value;
            }
        }

        public void Save()
        {
            RegistryKey settingsKey = SimpleRegistry.getSettingsKey();
            foreach (KeyValuePair<string, string> kv in settings)
            {
                try
                {
                    settingsKey.SetValue(kv.Key, kv.Value, RegistryValueKind.String);
                }
                catch (Exception e)
                {
                    ErrorHandler.HandleError(e.Message);
                }
            }
        }

        public bool SetAutoStart(bool value)
        {
            bool result = true;
            string oldValue = settings[APP_AUTOSTART];
            try
            {
                RegistryKey rk = Registry.LocalMachine.OpenSubKey(
                    "Software\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                if (rk == null) return false;
                if (value)
                {
                    rk.SetValue("Hauberk PC Doctor",
                        (object)Path.GetFullPath(Application.ExecutablePath));
                    settings[APP_AUTOSTART] = "Y";
                }
                else
                {
                    rk.DeleteValue("Hauberk PC Doctor");
                    settings[APP_AUTOSTART] = "N";
                }
                Save();
            }
            catch (Exception e)
            {
                result = false;
                settings[APP_AUTOSTART] = oldValue;
                ErrorHandler.HandleError(e.Message);
            }
            return result;
        }

        public void ReloadAutoStart()
        {
            if (settings.ContainsKey(APP_AUTOSTART))
            {
                if (settings[APP_AUTOSTART] == "Y")
                {
                    RegistryKey rk = Registry.LocalMachine.OpenSubKey(
                        "Software\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                    if (rk.GetValue("Hauberk PC Doctor") == null)
                    {
                        settings[APP_AUTOSTART] = "N";
                        Save();
                    }
                }
            }
        }

        protected void CreateDefault()
        {
            settings.Clear();
            settings.Add(APP_AUTOSCAN, "N");
            settings.Add(APP_AUTOFIX, "N");
            settings.Add(APP_AUTOSTART, "N");
            settings.Add(BUTTONS_CLOSE, "Close");
            settings.Add(BUTTONS_MINIMIZE, "Minimize");
            settings.Add(GAMING_PRINTERS, "Y");
            settings.Add(GAMING_SCANERS, "Y");
            settings.Add(GAMING_TABLET, "Y");
            settings.Add(GAMING_THEMES, "Y");
            settings.Add(GAMING_AERO, "Y");
            settings.Add(GAMING_REMOTEFILES, "Y");
            settings.Add(GAMING_SEARCH, "Y");
            settings.Add(GAMING_MCENTER, "Y");
            settings.Add(GAMING_UPDATE, "Y");
            settings.Add(GAMING_DEFRAG, "Y");
            settings.Add(GAMING_ERRORS, "Y");
            settings.Add(GAMING_OTHER, "Y");
            settings.Add(REGISTRATION_CODE, DEMO_REG_CODE);
            settings.Add(REGISTRATION_STATUS, "0");
            Save();
        }

        protected void Load()
        {
            settings.Clear();
            RegistryKey settingsKey = SimpleRegistry.getSettingsKey();
            if (settingsKey != null)
            {
                string[] subKeyNames = settingsKey.GetValueNames();
                foreach (string subKeyName in subKeyNames)
                {
                    try
                    {
                        settings.Add(subKeyName, Convert.ToString(settingsKey.GetValue(subKeyName)));
                    }
                    catch (Exception e)
                    {
                        ErrorHandler.HandleError(e.Message);
                    }
                }
            }
            if (settings.Count == 0)
            {
                CreateDefault();
            }
            //Проверка автозагрузки
            ReloadAutoStart();
        }
    }
}
